package interfaz;

import clases.*;
import java.math.BigDecimal;


import javax.swing.*;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.tree.*;

public class dlgPartidas3 extends javax.swing.JDialog {

    private ClsDatabase bd = new ClsDatabase();
    DefaultComboBoxModel modelpartidacodigo = new DefaultComboBoxModel();
    DefaultComboBoxModel modelCboUnidad = new DefaultComboBoxModel();
    ClsContraladorEventos controlEvent = new ClsContraladorEventos();
//    private ClsSeguridad seguridad = new ClsSeguridad();
//    private ClsSesion sesion = new ClsSesion(); 
    private ClsMetodos metodos = new ClsMetodos();
    DefaultComboBoxModel modelCboTipoInsumo = new DefaultComboBoxModel();
    int c1, c2;
    String accion = "N";
    String raiz_nivel = "0";
    String raiz_nombre = "";
    String raiz_codigo = "";
    boolean editando = false;
    //Object tabla_acu[][] = new Object[80][11];
    String array_arbol[][] = new String[100][3];
    //int total_filas = 0;
    boolean modificando = false;
    double mat_totales[] = new double[5];// total de montos

    public dlgPartidas3(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

        inicia();

    }

    public dlgPartidas3(java.awt.Frame parent, boolean modal, String partidita) {
        super(parent, modal);

        initComponents();

        inicia();
        ver_especifico(partidita);

    }

    public void inicia() {
        setLocation(5, 76);
        iconos_arbol();
        //setLocationRelativeTo(null);
        metodos._iconJDialog(this);
        metodos.tablaLongitudColumnas(tblInsumos, new int[]{40, 20, 250, 40, 60, 30, 0, 0});
        metodos.tablaLongitudColumnas(tablaAcu, new int[]{45, 20, 250, 50, 40, 60, 60, 60, 30, 0, 0, 0, 0, 0});
        metodos.tablaLongitudColumnas(tablaPartidas, new int[]{0, 433, 45, 0});
        metodos.comboboxLlenar(cboUnid, modelCboUnidad, "SELECT idunidad,simbolo FROM unidad");
        accion_nuevo();
        c1 = 0;
        c2 = 0;
        metodos.comboboxLlenarMas(cboTipoInsumo, modelCboTipoInsumo, "SELECT idinsumo_tipo,abreviatura FROM insumo_tipo");
        cargar_insumos("");

        c1 = 1;
        c2 = 1;
        //evento();
        tablaAcu.setDefaultRenderer(Object.class, new renderIcono());
        tblInsumos.setDefaultRenderer(Object.class, new renderIcono());
        alinear_tabla();
        cargar_partidas("", "");
        ocultar_columnas();
        arbol_llenado();
        bloquear(false);
    }

    public void bloquear(boolean v) {
        //Bloquear
        btnGuardar.setEnabled(v);
        tblInsumos.setEnabled(v);
    }

    public void ocultar_columnas() {
        metodos.tablaOcultarcolumnas(tablaPartidas, new int[]{0, 3});
        metodos.tablaOcultarcolumnas(tablaAcu, new int[]{9, 10, 11, 12, 13});
        metodos.tablaOcultarcolumnas(tblInsumos, new int[]{6, 7});
    }

    public void iconos_arbol() {
        DefaultTreeCellRenderer render = (DefaultTreeCellRenderer) jTree1.getCellRenderer();
        render.setLeafIcon(new ImageIcon(getClass().getResource("/resource/icon/principales/peque/tre_folder.png")));
        render.setOpenIcon(new ImageIcon(getClass().getResource("/resource/icon/principales/peque/tre_folder.png")));
        render.setClosedIcon(new ImageIcon(getClass().getResource("/resource/icon/principales/peque/tre_folder.png")));
    }

    public void arbol_llenado() {
        metodos.arbol_llenar(jTree1, "idnivel, nombre, nivel FROM partida_nivel", "WHERE estado='A' order by idnivel asc ;", array_arbol);
    }

    public void vistaAcu(String val) {
        String codigo;

        bloquear(true);
        if (val.equals("")) {
            codigo = metodos.generarCodigollaves("select substring(idpartida,3,4) from partida_base ", 4);
            codigo = "H_" + codigo;
            accion = "N";
            this.setName(this.getName() + "-Nuevo");
            txtNombrePartida.setText("");
            txtTotal.setText("0");
            mat_totales[0] = 0;
            txtRendimiento.setText("");
            cboUnid.setSelectedIndex(-1);
        } else {
            accion = "E";
            codigo = val;
            //System.out.println("-----------------------");

            Object[][] array_datos_partida = bd.select("partida_base", "idpartida,nombre,rendimiento,precio,tipo,idpartida_generica,idunidad", "idpartida='" + codigo + "'");
            txtNombrePartida.setText(array_datos_partida[0][1].toString());
            //jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(array_datos_partida[0][1].toString()));
            txtRendimiento.setText(metodos.redondeo_1(array_datos_partida[0][2].toString()));
            txtTotal.setText(array_datos_partida[0][3].toString());
            cboUnid.setSelectedIndex(modelCboUnidad.getIndexOf(array_datos_partida[0][6].toString()));
//            jLabel2.setText(cboUnid.getSelectedItem().toString());
            this.setName(this.getName() + "-Modificar");

        }
        // cargando valores por defectos
        txtCodigoPartida.setText(codigo);
        txtCodigoInsumo.setText("");
        txtDescripcionInsumo.setText("");
        txtCantidad.setText("");
        txtPrecio.setText("");
        cargar_partidas_detalle(codigo);
        total_montos();
    }

    public void alinear_tabla() {
        //izquierda
        DefaultTableCellRenderer modelocentrar = new DefaultTableCellRenderer();
        modelocentrar.setHorizontalAlignment(SwingConstants.RIGHT);
        tablaAcu.getColumnModel().getColumn(7).setCellRenderer(modelocentrar);
        tablaAcu.getColumnModel().getColumn(6).setCellRenderer(modelocentrar);
        tablaAcu.getColumnModel().getColumn(5).setCellRenderer(modelocentrar);
        tablaAcu.getColumnModel().getColumn(3).setCellRenderer(modelocentrar);
        tblInsumos.getColumnModel().getColumn(4).setCellRenderer(modelocentrar);
        //centrar
        DefaultTableCellRenderer modelocentrar2 = new DefaultTableCellRenderer();
        modelocentrar2.setHorizontalAlignment(SwingConstants.CENTER);
        tablaAcu.getColumnModel().getColumn(4).setCellRenderer(modelocentrar2);
        tblInsumos.getColumnModel().getColumn(3).setCellRenderer(modelocentrar2);

    }

    public void accion_nuevo() {
        if (accion.equals("N")) {
            btnOK.setEnabled(false);
//            jButton4.setEnabled(false);
//            jButton5.setEnabled(false);
        }
    }

    private boolean esmunmero(String cadena) {
        try {
            System.out.println(cadena);
            Double.parseDouble(cadena);
            return true;
        } catch (NumberFormatException nfe) {
            return false;
        }
    }

    public void evento_ok() {
        modificando = true;
        if (txtCodigoInsumo.getText().trim().length() == 0) {
//                    javax.swing.JOptionPane.showMessageDialog(this, "El ingrese el precio del insumo");
            return;
        }
        DefaultTableModel mdt = (DefaultTableModel) tablaAcu.getModel();
        int total_filas = mdt.getRowCount();
        for (int i = 0; i < total_filas; i++) {
            if (mdt.getValueAt(i, 0).toString().equals(txtCodigoInsumo.getText())) {
                if (txtPrecio.getText().trim().length() == 0) {
                    javax.swing.JOptionPane.showMessageDialog(this, "El ingrese el precio del insumo");
                    return;
                }
                if (txtCantidad.getText().trim().length() == 0) {
                    javax.swing.JOptionPane.showMessageDialog(this, "El ingrese la " + jLabel3.getText().substring(0, jLabel3.getText().length() - 1) + " del insumo");
                    return;
                }
                mdt.setValueAt(metodos.redondeo_2(txtCantidad.getText().replace(",", "")), i, 5);
                mdt.setValueAt(txtCantidad.getText().replace(",", ""), i, 11);//temp
                mdt.setValueAt(metodos.redondeo_2(txtPrecio.getText().replace(",", "")), i, 6);
                mdt.setValueAt(txtPrecio.getText().replace(",", ""), i, 12);//temp
                // calculo
                calculo(mdt, i, true);
                //fin calculo
                cargar_insumos(txtBuscar.getText());
                desgaste();
                total_montos();
                break;
            }
        }
    }

    public void evento() {
//        jTable1.addKeyListener(new KeyAdapter() {
//            @Override
//            public void keyReleased(KeyEvent e) {
//                if (jTable1.getSelectedRows().length > 0) {
//                    JOptionPane.showMessageDialog(jTable1, "No son molestos los popups?");
//                }
//            }
//        });
//        JOptionPane.showMessageDialog(null, "Holas");
        tablaAcu.getModel().addTableModelListener(new TableModelListener() {
            @Override
            public void tableChanged(final TableModelEvent e) {

//                DefaultTableModel mdt = (DefaultTableModel) tablaAcu.getModel();
                DefaultTableModel mdt = (DefaultTableModel) e.getSource();
//                int fila = mdt.getRowCount();
//                int columna = mdt.getColumnCount();


//                int fila = tablaAcu.getSelectedRow();
//                int columna = tablaAcu.getSelectedColumn();
                int fila = e.getFirstRow();
                int columna = e.getColumn();
//                int fila = jTable1.rowAtPoint(e.getPoint());
//                int columna = jTable1.columnAtPoint(e.getPoint());
                //System.err.println("TABLECHANGED(): Fila="+fila+" columna="+columna+" editando="+editando);
                if ((fila > -1) && (columna > -1)) {
                    if (fila != -1 && columna == 4 && editando) {
                        //cantidad
                        String valor = tablaAcu.getValueAt(fila, 3).toString();
                        System.err.println("vvalor=" + valor);
                        if (esmunmero(valor)) {
//                            editando=false;
                            System.out.println("Es un numero");
                            double cantida = Double.parseDouble(tablaAcu.getValueAt(fila, 3).toString());
                            double precio = Double.parseDouble(tablaAcu.getValueAt(fila, 5).toString());
                            double total = cantida * precio;
//                            mdt.setValueAt("2", fila, 6);
                            mdt.setValueAt(total, fila, 6);
//                             jTable1.setValueAt("dd", fila, 6);
                        } else {
//                            JOptionPane.showMessageDialog(tablaAcu, "no es numero");
                            mdt.setValueAt("", fila, 3);
//                            jTable1.editCellAt(fila, 4);
//                            Component aComp = jTable1.getEditorComponent();
//                            aComp.requestFocus();
                        }
                        editando = false;
                    }
                }
                //jTable1.setValueAt("dd", 0, 0);

            }
        });
    }

    public void cargar_insumos(String nombre) {
        metodos.tablaLlenaSql_defecto(tblInsumos,
                "i.idinsumo,i.idinsumo_tipo,i.nombre,u.simbolo,i.precio,'Agregar',i.idinsumo_tipo,i.subcatergoria ",
                "FROM insumo i,insumo_tipo t,unidad u "
                + "WHERE t.idinsumo_tipo=i.idinsumo_tipo and u.idunidad=i.idunidad and i.nombre like '%" + nombre + "%' and t.idinsumo_tipo like '" + modelCboTipoInsumo.getElementAt(cboTipoInsumo.getSelectedIndex()) + "%' "
                + "ORDER BY t.idinsumo_tipo asc, i.idinsumo asc ");
        iconos_tipo_insumo(tblInsumos, 1);
        iconos_accion(tblInsumos, 5);
        metodos.tablaRedondea(tblInsumos, new int[]{4});

    }

    public void iconos_accion(javax.swing.JTable tabla, int columna) {
        ImageIcon icon1 = new ImageIcon(getClass().getResource("/resource/icon/principales/peque/arriba_12.png"));
        ImageIcon icon2 = new ImageIcon(getClass().getResource("/resource/icon/principales/peque/mal_13.png"));

        int n = tabla.getRowCount();
        for (int i = 0; i < n; i++) {
            String valor = tabla.getValueAt(i, columna).toString();
            if (valor.equals("Agregar")) {
                tabla.setValueAt(new JLabel(icon1), i, columna);
            } else if (valor.equals("Quitar")) {
                tabla.setValueAt(new JLabel(icon2), i, columna);
            } else if (valor.equals("3")) {
                tabla.setValueAt(new JLabel(icon2), i, columna);
            } else {
                tabla.setValueAt(new JLabel(icon2), i, columna);
            }
        }
    }

    public void iconos_tipo_insumo(javax.swing.JTable tabla, int col_tipo) {
        ImageIcon icon1 = new ImageIcon(getClass().getResource("/resource/icon/principales/peque/ico_material_16.png"));
        ImageIcon icon2 = new ImageIcon(getClass().getResource("/resource/icon/principales/peque/ico_obrero.png"));
        ImageIcon icon3 = new ImageIcon(getClass().getResource("/resource/icon/principales/peque/ico_herramienta_12.png"));
        ImageIcon icon4 = new ImageIcon(getClass().getResource("/resource/icon/principales/peque/ico_servicios.png"));
        int n = tabla.getRowCount();
        for (int i = 0; i < n; i++) {
            String valor = tabla.getValueAt(i, col_tipo).toString();
            if (valor.equals("1")) {
                tabla.setValueAt(new JLabel(icon1), i, 1);
            } else if (valor.equals("2")) {
                tabla.setValueAt(new JLabel(icon2), i, 1);
            } else if (valor.equals("3")) {
                tabla.setValueAt(new JLabel(icon3), i, 1);
            } else if (valor.equals("4")) {
                tabla.setValueAt(new JLabel(icon4), i, 1);
            } else {
                tabla.setValueAt(new JLabel(icon3), i, 1);
            }
        }
    }

    public void redondeando_tabla() {
        DefaultTableModel mdt = (DefaultTableModel) tablaAcu.getModel();
        int n = mdt.getRowCount();
        String num;
        for (int i = 0; i < n; i++) {
            num = metodos.redondeo_2(mdt.getValueAt(i, 13));
            mdt.setValueAt(num, i, 7);
            num = metodos.redondeo_2(mdt.getValueAt(i, 12));
            mdt.setValueAt(num, i, 6);
            num = metodos.redondeo_2(mdt.getValueAt(i, 11));
            mdt.setValueAt(num, i, 5);
            num = metodos.redondeo_2(mdt.getValueAt(i, 3).toString().replace(",", ""));
            mdt.setValueAt(num, i, 3);
        }
    }

    public void tabla_cuadrilla_actualiza() {
        DefaultTableModel mdt = (DefaultTableModel) tablaAcu.getModel();
        int n = mdt.getRowCount();
        String tipo = "", sub_categoria = "";
        for (int i = 0; i < n; i++) {
            tipo = mdt.getValueAt(i, 9).toString();
            sub_categoria = mdt.getValueAt(i, 10).toString();
            if (tipo.equals("2") || (tipo.equals("3") && sub_categoria.equals("2"))) {
                //
            } else {
                mdt.setValueAt("", i, 3);
            }
        }
    }

    public void cargar_partidas_detalle(String nombre) {

        metodos.tablaLlenaSql_defecto(tablaAcu,
                " pd.idinsumo,i.idinsumo_tipo,i.nombre,pd.cuadrilla,u.simbolo,pd.cantidad,pd.precio_unitario,pd.precio_parcial,'Quitar',i.idinsumo_tipo,i.subcatergoria,pd.cantidad,pd.precio_unitario,pd.precio_parcial",
                "FROM partida_base_detalle pd, insumo i,insumo_tipo t,unidad u "
                + " where pd.idinsumo=i.idinsumo and  t.idinsumo_tipo=i.idinsumo_tipo and u.idunidad=i.idunidad and pd.idpartida='" + nombre + "' "
                + "ORDER BY t.idinsumo_tipo asc, i.idinsumo asc ");

        iconos_tipo_insumo(tablaAcu, 9);
        iconos_accion(tablaAcu, 8);
        redondeando_tabla();
        tabla_cuadrilla_actualiza();

    }

    public void agregar_insumo() {
        if (txtNombrePartida.getText().trim().length() == 0) {
            javax.swing.JOptionPane.showMessageDialog(this, "Ingrese el nombre de la partida");
            return;
        }
        if (cboUnid.getSelectedIndex() == -1) {
            javax.swing.JOptionPane.showMessageDialog(this, "Seleccione la unidad de la partida");
            return;
        }
        if (txtRendimiento.getText().trim().length() == 0) {
            javax.swing.JOptionPane.showMessageDialog(this, "Ingrese el rendimiento");
        }
        if (txtTotal.getText().trim().length() == 0) {
            txtTotal.setText("0");
        }
        int fila = tblInsumos.getSelectedRow();
        if (fila != -1) {
//            if (bd.verif_repite("select idpartida from partida_base where idpartida='" + jTextField1.getText() + "'") == false) {
//                bd.insert("partida_base", "idpartida,nombre,metrado,precio,tipo,idpartida_generica,idunidad,uso,estado", "'" + jTextField1.getText() + "','" + jTextField2.getText() + "','" + jTextField3.getText() + "','" + jTextField4.getText() + "','E','1','" + modelCboUnidad.getElementAt(jComboBox2.getSelectedIndex()) + "','N','A'");
//            }
            if (verfica_partida(tblInsumos.getValueAt(fila, 0).toString()) == false) {
                javax.swing.JOptionPane.showMessageDialog(this, "El insumo ya existe");
                return;
            }
            // agragando item
            DefaultTableModel mdt = (DefaultTableModel) tablaAcu.getModel();
            Object mat[] = new Object[14];
            mat[0] = tblInsumos.getValueAt(fila, 0);
            mat[1] = tblInsumos.getValueAt(fila, 6);
            mat[2] = tblInsumos.getValueAt(fila, 2);// descripcion
            //cuadrilla de mano de obra o de los equipos que estan afectados
            if (mat[1].equals("2") || (mat[1].equals("3") && tblInsumos.getValueAt(fila, 7).toString().equals("2"))) {
                mat[3] = metodos.redondeo_2(0);
            } else {
                mat[3] = "";
            }
            mat[4] = tblInsumos.getValueAt(fila, 3);//undidad
            mat[5] = metodos.redondeo_2(0);//cantidad

            mat[6] = metodos.redondeo_2(tblInsumos.getValueAt(fila, 4).toString().replace(",", ""));
            mat[7] = metodos.redondeo_2(0);
            mat[8] = "Quitar";
            mat[9] = mat[1];
            mat[10] = tblInsumos.getValueAt(fila, 7);
            //temp
            mat[11] = "0";// temp_cantidad
            mat[12] = mat[6];// temp_precio_unitario
            mat[13] = "0";// temp_precio_parcial
            mdt.addRow(mat);
            desgaste();
            total_montos();

            iconos_tipo_insumo(tablaAcu, 9);
            iconos_accion(tablaAcu, 8);
            // seleccionando
            String cod_insumo = mat[0].toString();
            metodos.seleccionar_tabla(tablaAcu, 0, cod_insumo);
            editar_insumo_verifica();
        }
    }

    public void calculo(DefaultTableModel mdt, int i, boolean opcion) {
        double subtotal = 0, precio_unitario = 0, cantidad = 0, cuadrilla = 0;
        String tipo_insumo = "", sub_categoria = "";
        tipo_insumo = mdt.getValueAt(i, 9).toString();
        // actualizando el rendimineto
        sub_categoria = mdt.getValueAt(i, 10).toString();
        // si es mano de obra y equipos que tienen rendimiento
        precio_unitario = Double.parseDouble(mdt.getValueAt(i, 12).toString());//temp
        if (tipo_insumo.equals("2") || (tipo_insumo.equals("3") && sub_categoria.equals("2"))) {
            String prueba_cuadrilla = mdt.getValueAt(i, 3).toString();
            if (prueba_cuadrilla.equals("")) {
                prueba_cuadrilla = "0";
                mdt.setValueAt(metodos.redondeo_2(prueba_cuadrilla), i, 3);
            }
            if (opcion) {
                prueba_cuadrilla = metodos.redondeo_1(txtCantidad.getText());
                mdt.setValueAt(metodos.redondeo_2(prueba_cuadrilla), i, 3);
            }
            //prueba_cuadrilla=prueba_cuadrilla.replace(",", "");
            cuadrilla = metodos.num_d(prueba_cuadrilla);
            cantidad = (cuadrilla * 8) / Double.parseDouble(txtRendimiento.getText());
            mdt.setValueAt(metodos.redondeo_2(cantidad), i, 5);//cantidad
            mdt.setValueAt(cantidad, i, 11);//temp_cantidad
            subtotal = cantidad * precio_unitario;
        } else {
            cantidad = Double.parseDouble(mdt.getValueAt(i, 11).toString());//cantidad
            subtotal = (cantidad * precio_unitario);
        }
        mdt.setValueAt(metodos.redondeo_2(subtotal), i, 7);
        mdt.setValueAt(subtotal, i, 13);//temp

        // actualizando insumos precios e insumos ok....
        bd.update("insumo", "precio='" + txtPrecio.getText().replace(",", "") + "'", " idinsumo='" + txtCodigoInsumo.getText() + "'");
    }

    public void total_montos() {
        //total
        double total_montos = 0;
        double valor1 = 0, valor2 = 0, valor3 = 0, valor4 = 0;
        double subtotal = 0;
        DefaultTableModel mdt = (DefaultTableModel) tablaAcu.getModel();
        String tipo_insumo = "";
        int total_filas = mdt.getRowCount();
        for (int i = 0; i < total_filas; i++) {
            tipo_insumo = mdt.getValueAt(i, 9).toString();
            subtotal = Double.parseDouble(mdt.getValueAt(i, 13).toString());
            total_montos = total_montos + subtotal;
            if (tipo_insumo.equals("1")) {
                valor1 = valor1 + subtotal;
            }
            if (tipo_insumo.equals("2")) {
                valor2 = valor2 + subtotal;
            }
            if (tipo_insumo.equals("3")) {
                valor3 = valor3 + subtotal;
            }
            if (tipo_insumo.equals("4")) {
                valor4 = valor4 + subtotal;
            }
        }
        label_total_5.setText(metodos.redondeo_2(valor1));
        label_total_6.setText(metodos.redondeo_2(valor2));
        label_total_7.setText(metodos.redondeo_2(valor3));
        label_total_8.setText(metodos.redondeo_2(valor4));
        txtTotal.setText(metodos.redondeo_2(total_montos));
        mat_totales[0] = total_montos;
        //redondeando_tabla();
    }

    public boolean verfica_partida(String codigo) {
        boolean va = true;
        DefaultTableModel mdt = (DefaultTableModel) tablaAcu.getModel();
        int total_filas = mdt.getRowCount();
        for (int i = 0; i < total_filas; i++) {
            if (mdt.getValueAt(i, 0).toString().equals(codigo)) {
                va = false;
                break;
            }
        }
        return va;
    }

    public double calculoManoObra() {
        //mano de obra
        double valor = 0;
        DefaultTableModel mdt = (DefaultTableModel) tablaAcu.getModel();
        int total_filas = mdt.getRowCount();
        for (int i = 0; i < total_filas; i++) {
            if (mdt.getValueAt(i, 9).toString().equals("2")) {
                valor = valor + Double.parseDouble(mdt.getValueAt(i, 13).toString());//temp_precio
            }
        }
        return valor;
    }

    public void desgaste() {
        //mano de obra
        double valor = 0;
        DefaultTableModel mdt = (DefaultTableModel) tablaAcu.getModel();
        int total_filas = mdt.getRowCount();
        for (int i = 0; i < total_filas; i++) {
            if (mdt.getValueAt(i, 4).toString().equals("%mo")) {
                double total_mano_obra = calculoManoObra();
                mdt.setValueAt(metodos.redondeo_2(total_mano_obra), i, 6);
                mdt.setValueAt(total_mano_obra, i, 12);//temp
                valor = ((Double.parseDouble(mdt.getValueAt(i, 11).toString()) * total_mano_obra) / 100);
                mdt.setValueAt(metodos.redondeo_2(valor), i, 7);
                mdt.setValueAt(valor, i, 13);//temp
                break;
            }
        }
    }

    public void quitar_insumos_partida() {
        int fila = tablaAcu.getSelectedRow();
        DefaultTableModel mdt = (DefaultTableModel) tablaAcu.getModel();
        mdt.removeRow(fila);
        desgaste();
        total_montos();

    }

    public void actualizacion_parciales_totales() {
        DefaultTableModel mdt = (DefaultTableModel) tablaAcu.getModel();
        int total_filas = mdt.getRowCount();
        for (int i = 0; i < total_filas; i++) {
            calculo(mdt, i, false);
        }
    }

    public void actulizar_montos_particulares() {
        // rendim=0;
        if (txtRendimiento.getText().trim().length() != 0) {
            if (Double.parseDouble(txtRendimiento.getText()) > 0) {
                actualizacion_parciales_totales();
                desgaste();
                total_montos();
            }
        }
    }

    public void actulizarPartida() {
        if (javax.swing.JOptionPane.showConfirmDialog(null, "¿Desea guardar los cambios efectuados en la partida?", "Mensaje", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == 0) {
            if (txtNombrePartida.getText().trim().length() == 0) {
                javax.swing.JOptionPane.showMessageDialog(this, "Ingrese el nombre de la partida");
                return;
            }
            if (cboUnid.getSelectedIndex() == -1) {
                javax.swing.JOptionPane.showMessageDialog(this, "Seleccione la unidad de la partida");
                return;
            }
            if (txtRendimiento.getText().trim().length() == 0) {
                javax.swing.JOptionPane.showMessageDialog(this, "Ingrese el rendimiento");
                return;
            }
            if (txtTotal.getText().trim().length() == 0) {
                txtTotal.setText("0");
                mat_totales[0] = 0;
            }
            // registrando en la tabla prtida base
            if (accion.equals("N")) {
                TreePath currentSelection = jTree1.getSelectionPath();
                if (currentSelection != null) {
                    raiz_nivel = Integer.toString(jTree1.getLeadSelectionPath().getPathCount());
                    int v = Integer.parseInt(raiz_nivel);
                    DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode) (currentSelection.getLastPathComponent());
                    raiz_codigo = arbol_id_buscar(getNodeIndex(jTree1, currentNode).trim());//codigo
                    if (v != 4) {
                        javax.swing.JOptionPane.showMessageDialog(this, "Seleccione un grupo el específico de las partidas");
                        return;
                    }
                    bd.insert_inyeccion("insert into partida_base (idpartida,nombre,rendimiento,precio,tipo,idpartida_generica,idunidad,uso,estado,idnivel)"
                            + " values (" + "'" + txtCodigoPartida.getText() + "'," + "?" + ",'" + txtRendimiento.getText() + "','" + mat_totales[0] + "','E','1','" + modelCboUnidad.getElementAt(cboUnid.getSelectedIndex()) + "','N','A','" + raiz_codigo + "'" + ") ", new String[]{txtNombrePartida.getText().replace("'", "")});
                } else {
                    javax.swing.JOptionPane.showMessageDialog(this, "Seleccione un grupo el específico de las partidas");
                    return;
                }
            } else {
                //bd.update("partida_base", "nombre='" + txtNombrePartida.getText() + "',metrado='" + txtRendimiento.getText() + "',precio='" + txtTotal.getText() + "',idunidad='" + modelCboUnidad.getElementAt(cboUnid.getSelectedIndex()) + "'", " idpartida='" + txtPartida.getText() + "'");
                bd.insert_inyeccion("update partida_base set nombre=" + "?" + ",rendimiento='" + txtRendimiento.getText() + "',precio='" + mat_totales[0] + "',idunidad='" + modelCboUnidad.getElementAt(cboUnid.getSelectedIndex()) + "' where idpartida='" + txtCodigoPartida.getText() + "' ", new String[]{txtNombrePartida.getText().replace("'", "")});

            }

            // validar ceros
            DefaultTableModel mdt = (DefaultTableModel) tablaAcu.getModel();
            int total_filas = mdt.getRowCount();
            String tipoInsumo = "";
            String sub_categoria = "";
            for (int i = 0; i < total_filas; i++) {
                double valida_cantidad = Double.parseDouble(mdt.getValueAt(i, 11).toString());
                if (valida_cantidad == 0) {
                    tipoInsumo = tablaAcu.getValueAt(i, 9).toString();
                    sub_categoria = tablaAcu.getValueAt(i, 10).toString();
                    if (tipoInsumo.equals("2") || (tipoInsumo.equals("3") && sub_categoria.equals("2"))) {
                        tipoInsumo = "Cuadrilla";
                    } else {
                        tipoInsumo = "Cantidad";
                    }
                    tablaAcu.changeSelection(i, 1, false, false);
                    editar_insumo_verifica();
                    javax.swing.JOptionPane.showMessageDialog(tablaAcu, "Debe ingresar la " + tipoInsumo + " de:\n" + mdt.getValueAt(i, 2).toString());

                    return;
                }
            }

            bd.delete("partida_base_detalle", "idpartida='" + txtCodigoPartida.getText() + "' ");
            for (int i = 0; i < total_filas; i++) {
                bd.insert("partida_base_detalle", "idpartida,idinsumo,cuadrilla,cantidad,precio_unitario,precio_parcial", "'" + txtCodigoPartida.getText() + "','"
                        + mdt.getValueAt(i, 0) + "','"
                        + mdt.getValueAt(i, 3).toString().replace(",", "") + "','" + mdt.getValueAt(i, 11) + "','" + mdt.getValueAt(i, 12) + "','" + mdt.getValueAt(i, 13) + "'");
            }

            btnOK.setEnabled(true);

            vistaAcu(txtCodigoPartida.getText());
            cargar_partida_procedadas_arbol();
            accion = "E";
            modificando = false;

        }
    }

    private void cargar_partidas(String nombre, String nivel) {
        metodos.tablaLlenaSql_defecto(tablaPartidas, " p.idpartida, p.nombre,u.simbolo,p.idnivel", "FROM partida_base p,unidad u where p.idunidad = u.idunidad and p.nombre like '%" + nombre + "%' and idnivel like '" + nivel + "%' order by p.nombre asc ");
    }

    public void ver_especifico(String val) {
        vistaAcu(val);
        txtBuscar.setText("");
        cargar_insumos(txtBuscar.getText());
    }

    public void editarVer() {
        if (modificando == true) {
            actulizarPartida();
        }
        editando = false;
        int fila = tablaPartidas.getSelectedRow();
        if (fila != -1) {
            vistaAcu(tablaPartidas.getValueAt(fila, 0).toString());
            txtBuscar.setText("");
            cargar_insumos(txtBuscar.getText());

        } else {
            javax.swing.JOptionPane.showMessageDialog(this, "Seleccione una partida procesada");
        }
        editando = true;
        modificando = false;
    }

    public void setTreeState(JTree tree, boolean expanded) {
        Object root = tree.getModel().getRoot();
        setTreeState(tree, new TreePath(root), expanded);
    }

    public void setTreeState(JTree tree, TreePath path, boolean expanded) {
        Object lastNode = path.getLastPathComponent();
        for (int i = 0; i < tree.getModel().getChildCount(lastNode); i++) {
            Object child = tree.getModel().getChild(lastNode, i);
            TreePath pathToChild = path.pathByAddingChild(child);
            setTreeState(tree, pathToChild, expanded);
        }
        if (expanded) {
            tree.expandPath(path);
        } else {
            tree.collapsePath(path);
        }
    }

    public void eliminar_partida() {
        int fila = tablaPartidas.getSelectedRow();
        if (fila != -1) {
            if (javax.swing.JOptionPane.showConfirmDialog(null, "Esta seguro de eliminar la partida", "Mensaje", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == 0) {

                bd.delete("partida_base_detalle", "idpartida='" + tablaPartidas.getValueAt(tablaPartidas.getSelectedRow(), 0).toString() + "' ");
                bd.delete("partida_base", "idpartida='" + tablaPartidas.getValueAt(tablaPartidas.getSelectedRow(), 0).toString() + "' ");
                cargar_partidas("", "");
                //cargar_partidas_detalle("--");
                //javax.swing.JOptionPane.showMessageDialog(null, "");
            }
        } else {
            javax.swing.JOptionPane.showMessageDialog(this, "Seleccione la partida");
        }
    }

    public void editar_insumo_verifica() {
        int fila = tablaAcu.getSelectedRow();
        if (fila != -1) {
            txtCodigoInsumo.setText(tablaAcu.getValueAt(fila, 0).toString());
            txtDescripcionInsumo.setText(tablaAcu.getValueAt(fila, 2).toString());
            txtPrecio.setText(tablaAcu.getValueAt(fila, 12).toString());
            txtPrecio.setEnabled(true);

            btnOK.setEnabled(true);
            //cuadrilla solo para mano de obra y equipos afectados
            String tipoInsumo = tablaAcu.getValueAt(fila, 9).toString();
            String sub_categoria = tablaAcu.getValueAt(fila, 10).toString();
            if (tipoInsumo.equals("2") || (tipoInsumo.equals("3") && sub_categoria.equals("2"))) {
                jLabel3.setText("Cuad:");
                txtCantidad.setText(tablaAcu.getValueAt(fila, 3).toString().replace(",", ""));
            } else {
                jLabel3.setText("Cant:");
                txtCantidad.setText(tablaAcu.getValueAt(fila, 11).toString());
            }
            if (tablaAcu.getValueAt(fila, 4).equals("%mo")) {
                txtPrecio.setEnabled(false);
                jLabel3.setText("%:");
                txtCantidad.setText(tablaAcu.getValueAt(fila, 11).toString());
            }
            //seleccionado y limpiando
            txtBuscar.setText("");
            cboTipoInsumo.setSelectedIndex(0);
            cargar_insumos("");
            metodos.seleccionar_tabla(tblInsumos, 2, txtDescripcionInsumo.getText());
        }
    }

    public String getNodeIndex(JTree tree, TreeNode node) {
        TreeNode root = (TreeNode) tree.getModel().getRoot();
        if (node == root) {
            return "";
        }
        TreeNode parent = node.getParent();
        if (parent == null) {
            return null;
        }
        String parentIndex = getNodeIndex(tree, parent);
        if (parentIndex == null) {
            return null;
        }
        return parentIndex + "." + parent.getIndex(node);
    }

    public String arbol_id_buscar(String valor) {
        String v = "";
        for (int i = 0; i < array_arbol.length; i++) {
            if (array_arbol[i][2] != null) {
//                System.out.println(array_arbol[i][2]);
                if (array_arbol[i][2].equals(valor)) {
                    v = array_arbol[i][0];
                    //break;
                }
            }
        }
        return v;
    }

    public void operaciones_grupo_parttidas(int opcion) {
        int v = jTree1.getLeadSelectionRow();
        if (v != -1) {
            TreePath currentSelection = jTree1.getSelectionPath();
            if (currentSelection != null) {
                raiz_nivel = Integer.toString(jTree1.getLeadSelectionPath().getPathCount());// NIVEL
                if (opcion == 1) {
                    //nuevo
                    if (raiz_nivel.equals("4")) {
                        javax.swing.JOptionPane.showMessageDialog(this, "No se puede crear mas  categorias");
                    } else {
                        raiz_nombre = jTree1.getLastSelectedPathComponent().toString();// NOMBRE
                        DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode) (currentSelection.getLastPathComponent());
                        raiz_codigo = arbol_id_buscar(getNodeIndex(jTree1, currentNode).trim());//codigo
                        dlgIndiceEditar dialog = new dlgIndiceEditar(new javax.swing.JFrame(), true, raiz_nivel, raiz_nombre, raiz_codigo, opcion);
                        dialog.setVisible(true);
                        arbol_llenado();
                        txtCodigoPartida.requestFocus();
                    }
                } else {
                    //editar
                    raiz_nombre = jTree1.getLastSelectedPathComponent().toString();// NOMBRE
                    DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode) (currentSelection.getLastPathComponent());
                    raiz_codigo = arbol_id_buscar(getNodeIndex(jTree1, currentNode).trim());//codigo
                    dlgIndiceEditar dialog = new dlgIndiceEditar(new javax.swing.JFrame(), true, raiz_nivel, raiz_nombre, raiz_codigo, opcion);
                    dialog.setVisible(true);
                    arbol_llenado();
                    txtCodigoPartida.requestFocus();
                }
            }
        } else {
            String mensaje = "Seleccione un grupo de partida";
            if (opcion == 1) {
                mensaje = "Seleccione un grupo de partida\nDonde se creara el nuevo grupo";
            }
            javax.swing.JOptionPane.showMessageDialog(this, mensaje);
        }
    }

    public void cargar_partida_procedadas_arbol() {
        int v = jTree1.getLeadSelectionRow();
        if (v != -1) {
            TreePath currentSelection = jTree1.getSelectionPath();
            if (currentSelection != null) {
                raiz_nivel = Integer.toString(jTree1.getLeadSelectionPath().getPathCount());// NIVEL
                raiz_nombre = jTree1.getLastSelectedPathComponent().toString();// NOMBRE
                DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode) (currentSelection.getLastPathComponent());
                raiz_codigo = arbol_id_buscar(getNodeIndex(jTree1, currentNode).trim());//codigo
                Object[][] cantidad = bd.select("partida_base", "count(idpartida)", "nombre like '%" + "" + "%' and idnivel like '" + raiz_codigo + "%'");
                String cant = "0";
                if (cantidad != null) {
                    cant = cantidad[0][0].toString();
                }
                jPanel7.setBorder(javax.swing.BorderFactory.createTitledBorder("Partidas procesadas: " + cant + " de " + raiz_nombre));
                cargar_partidas("", raiz_codigo);

                txtBuscar1.setText("");
            }
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        panelAcu = new javax.swing.JPanel();
        txtNombrePartida = new javax.swing.JTextField();
        txtCodigoPartida = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        txtRendimiento = new javax.swing.JTextField();
        txtTotal = new javax.swing.JTextField();
        cboUnid = new javax.swing.JComboBox();
        jLabel14 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaAcu = new javax.swing.JTable();
        btnGuardar = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        label_total_1 = new javax.swing.JLabel();
        label_total_2 = new javax.swing.JLabel();
        label_total_4 = new javax.swing.JLabel();
        label_total_3 = new javax.swing.JLabel();
        label_total_5 = new javax.swing.JLabel();
        label_total_6 = new javax.swing.JLabel();
        label_total_7 = new javax.swing.JLabel();
        label_total_8 = new javax.swing.JLabel();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        tblInsumos = new javax.swing.JTable();
        jLabel4 = new javax.swing.JLabel();
        txtBuscar = new javax.swing.JTextField();
        cboTipoInsumo = new javax.swing.JComboBox();
        jLabel9 = new javax.swing.JLabel();
        btnLimpiar1 = new javax.swing.JButton();
        btnLimpiar = new javax.swing.JButton();
        jPanel8 = new javax.swing.JPanel();
        jScrollPane4 = new javax.swing.JScrollPane();
        jTree1 = new javax.swing.JTree();
        jToolBar2 = new javax.swing.JToolBar();
        btnNuevoCategoria = new javax.swing.JButton();
        btnNuevoCategoria1 = new javax.swing.JButton();
        btnEliminarCategoria = new javax.swing.JButton();
        jPanel7 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tablaPartidas = new javax.swing.JTable();
        jLabel13 = new javax.swing.JLabel();
        txtBuscar1 = new javax.swing.JTextField();
        jToolBar1 = new javax.swing.JToolBar();
        btnNuevoPartidasR = new javax.swing.JButton();
        btnCopiarPartidasR = new javax.swing.JButton();
        btnEliminarPartidasR = new javax.swing.JButton();
        jPanel5 = new javax.swing.JPanel();
        txtCodigoInsumo = new javax.swing.JTextField();
        txtDescripcionInsumo = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        txtPrecio = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtCantidad = new javax.swing.JTextField();
        btnOK = new javax.swing.JButton();
        jLabel10 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Análisis de Costos Unitarios");

        jPanel2.setBackground(new java.awt.Color(225, 235, 247));
        jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        panelAcu.setBackground(new java.awt.Color(153, 204, 255));
        panelAcu.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Análisis de Costos Unitarios", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, null, new java.awt.Color(0, 41, 99)));
        panelAcu.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
        panelAcu.add(txtNombrePartida, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 32, 430, -1));

        txtCodigoPartida.setEditable(false);
        panelAcu.add(txtCodigoPartida, new org.netbeans.lib.awtextra.AbsoluteConstraints(64, 32, 56, -1));

        jLabel1.setText("Partida:");
        panelAcu.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 32, -1, 25));

        jLabel5.setText("Rendim:");
        jLabel5.setToolTipText("Rendimiento");
        panelAcu.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 60, 50, 25));

        jLabel6.setText("CU:");
        panelAcu.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(410, 60, 30, 25));

        txtRendimiento.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        txtRendimiento.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtRendimientoKeyReleased(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtRendimientoKeyTyped(evt);
            }
        });
        panelAcu.add(txtRendimiento, new org.netbeans.lib.awtextra.AbsoluteConstraints(64, 60, 56, -1));

        txtTotal.setEditable(false);
        txtTotal.setBackground(new java.awt.Color(242, 242, 242));
        txtTotal.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        txtTotal.setEnabled(false);
        txtTotal.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtTotalKeyTyped(evt);
            }
        });
        panelAcu.add(txtTotal, new org.netbeans.lib.awtextra.AbsoluteConstraints(440, 60, 110, -1));

        cboUnid.setToolTipText("Unidad");
        cboUnid.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cboUnidActionPerformed(evt);
            }
        });
        panelAcu.add(cboUnid, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 60, 60, -1));

        jLabel14.setText("/ Dia");
        panelAcu.add(jLabel14, new org.netbeans.lib.awtextra.AbsoluteConstraints(185, 60, 30, 25));

        tablaAcu.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Cod.", "", "Descripción", "Cuad.", "Und.", "Cant.", "P. Unitario", "P. Parcial", "Quitar", "idtipo", "subcategoria", "cant_temp", "Puni_temp", "Ppar_temp"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, false, false, false, false, true, true, true
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tablaAcu.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tablaAcu.getTableHeader().setReorderingAllowed(false);
        tablaAcu.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablaAcuMouseClicked(evt);
            }
        });
        tablaAcu.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                tablaAcuKeyTyped(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tablaAcuKeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(tablaAcu);

        panelAcu.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 94, 730, 242));

        btnGuardar.setForeground(new java.awt.Color(3, 90, 180));
        btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/guardar.png"))); // NOI18N
        btnGuardar.setText("Guardar");
        btnGuardar.setFocusable(false);
        btnGuardar.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnGuardar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });
        panelAcu.add(btnGuardar, new org.netbeans.lib.awtextra.AbsoluteConstraints(640, 0, 100, 30));

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jPanel1.setOpaque(false);
        jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        label_total_1.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        label_total_1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/ico_material_16.png"))); // NOI18N
        label_total_1.setToolTipText("Materiales");
        label_total_1.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        jPanel1.add(label_total_1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 25, -1));

        label_total_2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        label_total_2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/ico_obrero.png"))); // NOI18N
        label_total_2.setToolTipText("Mano de obra");
        label_total_2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jPanel1.add(label_total_2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 33, 25, -1));

        label_total_4.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        label_total_4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/ico_servicios.png"))); // NOI18N
        label_total_4.setToolTipText("Servicios");
        label_total_4.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        jPanel1.add(label_total_4, new org.netbeans.lib.awtextra.AbsoluteConstraints(96, 33, 20, -1));

        label_total_3.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        label_total_3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/ico_herramienta_12.png"))); // NOI18N
        label_total_3.setToolTipText("Equipos y herramientas");
        label_total_3.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        jPanel1.add(label_total_3, new org.netbeans.lib.awtextra.AbsoluteConstraints(96, 10, 20, -1));

        label_total_5.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        label_total_5.setText("0.00");
        label_total_5.setToolTipText("Materiales");
        label_total_5.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        jPanel1.add(label_total_5, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 10, 60, -1));

        label_total_6.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        label_total_6.setText("0.00");
        label_total_6.setToolTipText("Mano de obra");
        label_total_6.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        jPanel1.add(label_total_6, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 33, 60, -1));

        label_total_7.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        label_total_7.setText("0.00");
        label_total_7.setToolTipText("Equipos y herramientas");
        label_total_7.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        jPanel1.add(label_total_7, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 10, 60, -1));

        label_total_8.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        label_total_8.setText("0.00");
        label_total_8.setToolTipText("Servicios");
        label_total_8.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        jPanel1.add(label_total_8, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 33, 60, -1));

        panelAcu.add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(560, 30, 180, 60));

        jPanel2.add(panelAcu, new org.netbeans.lib.awtextra.AbsoluteConstraints(530, 10, 750, 350));

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jPanel4.setOpaque(false);
        jPanel4.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        tblInsumos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Cód.", "", "Descripción", "Und", "Precio", "Añadir", "tipo_insumo", "subcategoria"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, true
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblInsumos.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tblInsumos.getTableHeader().setReorderingAllowed(false);
        tblInsumos.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblInsumosMouseClicked(evt);
            }
        });
        jScrollPane3.setViewportView(tblInsumos);

        jPanel4.add(jScrollPane3, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 31, 730, 150));

        jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        jLabel4.setText("Buscar insumo:");
        jPanel4.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 6, 90, -1));

        txtBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtBuscarActionPerformed(evt);
            }
        });
        txtBuscar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtBuscarKeyReleased(evt);
            }
        });
        jPanel4.add(txtBuscar, new org.netbeans.lib.awtextra.AbsoluteConstraints(106, 3, 270, -1));

        cboTipoInsumo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cboTipoInsumo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cboTipoInsumoActionPerformed(evt);
            }
        });
        jPanel4.add(cboTipoInsumo, new org.netbeans.lib.awtextra.AbsoluteConstraints(649, 3, 90, -1));

        jLabel9.setText("Tipo insumo:");
        jPanel4.add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(577, 6, -1, -1));

        btnLimpiar1.setText("BD Insumos");
        btnLimpiar1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLimpiar1ActionPerformed(evt);
            }
        });
        jPanel4.add(btnLimpiar1, new org.netbeans.lib.awtextra.AbsoluteConstraints(470, 0, 100, -1));

        btnLimpiar.setText("Limpiar");
        btnLimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLimpiarActionPerformed(evt);
            }
        });
        jPanel4.add(btnLimpiar, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 0, -1, -1));

        jPanel2.add(jPanel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(530, 414, 750, 192));

        jPanel8.setBorder(javax.swing.BorderFactory.createTitledBorder("Grupos de partidas"));
        jPanel8.setOpaque(false);
        jPanel8.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("root");
        javax.swing.tree.DefaultMutableTreeNode treeNode2 = new javax.swing.tree.DefaultMutableTreeNode("Partidas");
        javax.swing.tree.DefaultMutableTreeNode treeNode3 = new javax.swing.tree.DefaultMutableTreeNode("Basicos");
        treeNode2.add(treeNode3);
        treeNode3 = new javax.swing.tree.DefaultMutableTreeNode("Construcción");
        treeNode2.add(treeNode3);
        treeNode3 = new javax.swing.tree.DefaultMutableTreeNode("Saneamiento");
        javax.swing.tree.DefaultMutableTreeNode treeNode4 = new javax.swing.tree.DefaultMutableTreeNode("captación");
        treeNode3.add(treeNode4);
        treeNode2.add(treeNode3);
        treeNode1.add(treeNode2);
        treeNode2 = new javax.swing.tree.DefaultMutableTreeNode("sergio");
        treeNode3 = new javax.swing.tree.DefaultMutableTreeNode("miguel");
        treeNode2.add(treeNode3);
        treeNode1.add(treeNode2);
        jTree1.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
        jTree1.setFocusable(false);
        jTree1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jTree1MousePressed(evt);
            }
        });
        jTree1.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                jTree1ValueChanged(evt);
            }
        });
        jScrollPane4.setViewportView(jTree1);

        jPanel8.add(jScrollPane4, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 50, 500, 175));

        jToolBar2.setFloatable(false);
        jToolBar2.setRollover(true);
        jToolBar2.setOpaque(false);

        btnNuevoCategoria.setForeground(new java.awt.Color(3, 90, 180));
        btnNuevoCategoria.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/agregar.png"))); // NOI18N
        btnNuevoCategoria.setText("Nuevo");
        btnNuevoCategoria.setFocusable(false);
        btnNuevoCategoria.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnNuevoCategoria.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoCategoriaActionPerformed(evt);
            }
        });
        jToolBar2.add(btnNuevoCategoria);

        btnNuevoCategoria1.setForeground(new java.awt.Color(3, 90, 180));
        btnNuevoCategoria1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/editar.png"))); // NOI18N
        btnNuevoCategoria1.setText("Editar");
        btnNuevoCategoria1.setFocusable(false);
        btnNuevoCategoria1.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnNuevoCategoria1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoCategoria1ActionPerformed(evt);
            }
        });
        jToolBar2.add(btnNuevoCategoria1);

        btnEliminarCategoria.setForeground(new java.awt.Color(3, 90, 180));
        btnEliminarCategoria.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/borrar.png"))); // NOI18N
        btnEliminarCategoria.setText("Eliminar");
        btnEliminarCategoria.setFocusable(false);
        btnEliminarCategoria.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnEliminarCategoria.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarCategoriaActionPerformed(evt);
            }
        });
        jToolBar2.add(btnEliminarCategoria);

        jPanel8.add(jToolBar2, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 16, 500, -1));

        jPanel2.add(jPanel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(5, 10, 520, 235));

        jPanel7.setBorder(javax.swing.BorderFactory.createTitledBorder("Partidas procesadas"));
        jPanel7.setOpaque(false);
        jPanel7.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        tablaPartidas.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Id", "Descripción", "Und", "nivel"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, true, true
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tablaPartidas.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        tablaPartidas.setGridColor(new java.awt.Color(225, 235, 247));
        tablaPartidas.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tablaPartidas.getTableHeader().setReorderingAllowed(false);
        tablaPartidas.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                tablaPartidasMousePressed(evt);
            }
        });
        tablaPartidas.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tablaPartidasKeyReleased(evt);
            }
        });
        jScrollPane2.setViewportView(tablaPartidas);

        jPanel7.add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 81, 500, 265));

        jLabel13.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        jLabel13.setText("Buscar:");
        jPanel7.add(jLabel13, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 53, -1, 25));

        txtBuscar1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtBuscar1KeyReleased(evt);
            }
        });
        jPanel7.add(txtBuscar1, new org.netbeans.lib.awtextra.AbsoluteConstraints(56, 53, 450, -1));

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);
        jToolBar1.setOpaque(false);

        btnNuevoPartidasR.setForeground(new java.awt.Color(3, 90, 180));
        btnNuevoPartidasR.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/agregar.png"))); // NOI18N
        btnNuevoPartidasR.setText("Nuevo");
        btnNuevoPartidasR.setFocusable(false);
        btnNuevoPartidasR.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnNuevoPartidasR.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoPartidasRActionPerformed(evt);
            }
        });
        jToolBar1.add(btnNuevoPartidasR);

        btnCopiarPartidasR.setForeground(new java.awt.Color(3, 90, 180));
        btnCopiarPartidasR.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/duplicar.png"))); // NOI18N
        btnCopiarPartidasR.setText("Copiar");
        btnCopiarPartidasR.setFocusable(false);
        btnCopiarPartidasR.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnCopiarPartidasR.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCopiarPartidasRActionPerformed(evt);
            }
        });
        jToolBar1.add(btnCopiarPartidasR);

        btnEliminarPartidasR.setForeground(new java.awt.Color(3, 90, 180));
        btnEliminarPartidasR.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/borrar.png"))); // NOI18N
        btnEliminarPartidasR.setText("Eliminar");
        btnEliminarPartidasR.setFocusable(false);
        btnEliminarPartidasR.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnEliminarPartidasR.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarPartidasRActionPerformed(evt);
            }
        });
        jToolBar1.add(btnEliminarPartidasR);

        jPanel7.add(jToolBar1, new org.netbeans.lib.awtextra.AbsoluteConstraints(12, 16, 500, -1));

        jPanel2.add(jPanel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(5, 250, 520, 358));

        jPanel5.setBackground(new java.awt.Color(153, 204, 255));
        jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jPanel5.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        txtCodigoInsumo.setEditable(false);
        txtCodigoInsumo.setBackground(new java.awt.Color(242, 242, 242));
        txtCodigoInsumo.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jPanel5.add(txtCodigoInsumo, new org.netbeans.lib.awtextra.AbsoluteConstraints(8, 10, 90, -1));

        txtDescripcionInsumo.setBackground(new java.awt.Color(242, 242, 242));
        txtDescripcionInsumo.setEditable(false);
        txtDescripcionInsumo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtDescripcionInsumoKeyTyped(evt);
            }
        });
        jPanel5.add(txtDescripcionInsumo, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 10, 320, -1));

        jLabel8.setText("Precio:");
        jPanel5.add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(550, 10, 40, 25));

        txtPrecio.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        txtPrecio.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtPrecioFocusGained(evt);
            }
        });
        txtPrecio.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtPrecioKeyTyped(evt);
            }
        });
        jPanel5.add(txtPrecio, new org.netbeans.lib.awtextra.AbsoluteConstraints(590, 10, 70, -1));

        jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel3.setText("Cant:");
        jPanel5.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(420, 10, 40, 25));

        txtCantidad.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        txtCantidad.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtCantidadFocusGained(evt);
            }
        });
        txtCantidad.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtCantidadKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtCantidadKeyTyped(evt);
            }
        });
        jPanel5.add(txtCantidad, new org.netbeans.lib.awtextra.AbsoluteConstraints(460, 10, 80, -1));

        btnOK.setText("Ok");
        btnOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOKActionPerformed(evt);
            }
        });
        jPanel5.add(btnOK, new org.netbeans.lib.awtextra.AbsoluteConstraints(680, 10, 60, -1));

        jPanel2.add(jPanel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(530, 360, 750, 50));

        jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/fondo_dialog.jpg"))); // NOI18N
        jPanel2.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 450, -1));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 1340, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 609, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tblInsumosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblInsumosMouseClicked
        //agragar_datos();
        if (evt.getClickCount() == 2) {
            int fila = tblInsumos.getSelectedRow();
            int columna = tblInsumos.getSelectedColumn();
            if (fila != -1 && (columna == 2 || columna == 5)) {
                modificando = true;
                agregar_insumo();
                //javax.swing.JOptionPane.showMessageDialog(null, "salio");
            }
            if (fila != -1 && columna == 3) {
//                dlgPartidaPrecioModifica dialog = new dlgPartidaPrecioModifica(new javax.swing.JFrame(), true, tblInsumos.getValueAt(fila, 0).toString(), tblInsumos.getValueAt(fila, 2).toString(), tblInsumos.getValueAt(fila, 3).toString(), "");
//                dialog.setVisible(true);
                //javax.swing.JOptionPane.showMessageDialog(null, "salio");
            }
        }

    }//GEN-LAST:event_tblInsumosMouseClicked

    private void txtBuscarKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBuscarKeyReleased
        cargar_insumos(txtBuscar.getText());
    }//GEN-LAST:event_txtBuscarKeyReleased

    private void txtBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtBuscarActionPerformed
    }//GEN-LAST:event_txtBuscarActionPerformed

    private void cboTipoInsumoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cboTipoInsumoActionPerformed
        if (c1 == 1) {
            cargar_insumos(txtBuscar.getText());
        }
    }//GEN-LAST:event_cboTipoInsumoActionPerformed

    private void txtRendimientoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtRendimientoKeyTyped
        controlEvent.soloNumerosDecimales(evt, txtRendimiento, 2);
    }//GEN-LAST:event_txtRendimientoKeyTyped

    private void txtTotalKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtTotalKeyTyped
    }//GEN-LAST:event_txtTotalKeyTyped

    private void txtPrecioKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPrecioKeyTyped
        if (evt.getKeyChar() == 10) {
            evento_ok();
        }
        controlEvent.soloNumerosDecimales(evt, txtPrecio, 2);
    }//GEN-LAST:event_txtPrecioKeyTyped

    private void txtCantidadKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCantidadKeyTyped

        if (evt.getKeyChar() == 10) {
            evento_ok();
        }
        controlEvent.soloNumerosDecimales(evt, txtCantidad, 2);
    }//GEN-LAST:event_txtCantidadKeyTyped

    private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOKActionPerformed
        evento_ok();
    }//GEN-LAST:event_btnOKActionPerformed

    private void btnNuevoPartidasRActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoPartidasRActionPerformed
        if (modificando == true) {
            actulizarPartida();
        }
        vistaAcu("");
    }//GEN-LAST:event_btnNuevoPartidasRActionPerformed

    private void btnEliminarPartidasRActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarPartidasRActionPerformed
        eliminar_partida();
    }//GEN-LAST:event_btnEliminarPartidasRActionPerformed

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        actulizarPartida();
    }//GEN-LAST:event_btnGuardarActionPerformed

    private void tablaPartidasKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tablaPartidasKeyReleased
        editarVer();
    }//GEN-LAST:event_tablaPartidasKeyReleased

    private void txtBuscar1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBuscar1KeyReleased
        cargar_partidas(txtBuscar1.getText(), "");
    }//GEN-LAST:event_txtBuscar1KeyReleased

    private void tablaAcuMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaAcuMouseClicked
        editar_insumo_verifica();

        if (evt.getClickCount() == 2) {
            int fila = tablaAcu.getSelectedRow();
            int columna = tablaAcu.getSelectedColumn();

            if (fila != -1 && columna == 8) {
                quitar_insumos_partida();
            }
        }
    }//GEN-LAST:event_tablaAcuMouseClicked

    private void tablaAcuKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tablaAcuKeyReleased
        editar_insumo_verifica();
        editando = true;
    }//GEN-LAST:event_tablaAcuKeyReleased

    private void tablaAcuKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tablaAcuKeyTyped
        if (tablaAcu.getSelectedRows().length > 0) {
        }
    }//GEN-LAST:event_tablaAcuKeyTyped

    private void cboUnidActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cboUnidActionPerformed
        if (c2 == 1) {
            if (cboUnid.getSelectedIndex() != -1) {
//                jLabel2.setText(cboUnid.getSelectedItem().toString());
            }
        }
    }//GEN-LAST:event_cboUnidActionPerformed

    private void jTree1MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTree1MousePressed
        cargar_partida_procedadas_arbol();
    }//GEN-LAST:event_jTree1MousePressed

    private void txtDescripcionInsumoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDescripcionInsumoKeyTyped
        // TODO add your handling code here:
    }//GEN-LAST:event_txtDescripcionInsumoKeyTyped

    private void btnNuevoCategoriaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoCategoriaActionPerformed
        operaciones_grupo_parttidas(1);
    }//GEN-LAST:event_btnNuevoCategoriaActionPerformed

    private void btnEliminarCategoriaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarCategoriaActionPerformed
        int v = jTree1.getLeadSelectionRow();
        if (v != -1) {
            if (v == 0) {
                javax.swing.JOptionPane.showMessageDialog(this, "No se puede eliminar esta categoria");
            } else {
                if (javax.swing.JOptionPane.showConfirmDialog(null, "Esta seguro de eliminar la categoria", "Mensaje", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == 0) {
                    TreePath currentSelection = jTree1.getSelectionPath();
                    if (currentSelection != null) {

                        DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode) (currentSelection.getLastPathComponent());
                        raiz_codigo = arbol_id_buscar(getNodeIndex(jTree1, currentNode).trim());//codigo
                        //System.out.println(raiz3+" "+ currentNode);
                        if (bd.verif_repite("SELECT idnivel FROM partida_base where idnivel like '" + raiz_codigo + "%';") == false) {
                            bd.delete("partida_nivel", "idnivel like '" + raiz_codigo + "%' ");
                            arbol_llenado();
                            //cargar_partidas_detalle("--");
//                        javax.swing.JOptionPane.showMessageDialog(null, "Se eliminó correctamente");
                        } else {
                            javax.swing.JOptionPane.showMessageDialog(this, "No se puede eliminar este grupo, tiene partidas creadas");
                        }
                    }
                }
            }
        } else {
            javax.swing.JOptionPane.showMessageDialog(this, "Seleccione un grupo de partida");
        }
    }//GEN-LAST:event_btnEliminarCategoriaActionPerformed

    private void btnCopiarPartidasRActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCopiarPartidasRActionPerformed
        int fila = tablaPartidas.getSelectedRow();
        if (fila != -1) {
            dlgPartidaCopiar dialog = new dlgPartidaCopiar(new javax.swing.JFrame(), true, tablaPartidas.getValueAt(fila, 0).toString(), tablaPartidas.getValueAt(fila, 1).toString());
            dialog.setVisible(true);
            cargar_partidas("", "");
        } else {
            javax.swing.JOptionPane.showMessageDialog(this, "Seleccione la partida");
        }
    }//GEN-LAST:event_btnCopiarPartidasRActionPerformed

    private void tablaPartidasMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaPartidasMousePressed
        editarVer();
    }//GEN-LAST:event_tablaPartidasMousePressed

    private void txtCantidadKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCantidadKeyPressed
//        controlEvent.elimina_copiar(evt);
    }//GEN-LAST:event_txtCantidadKeyPressed

    private void jTree1ValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_jTree1ValueChanged
        // TreePath path = evt.getPath();
    }//GEN-LAST:event_jTree1ValueChanged

    private void txtCantidadFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtCantidadFocusGained
        metodos.seleccionar_texto(txtCantidad);
    }//GEN-LAST:event_txtCantidadFocusGained

    private void txtPrecioFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtPrecioFocusGained
        metodos.seleccionar_texto(txtPrecio);
    }//GEN-LAST:event_txtPrecioFocusGained

    private void btnLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLimpiarActionPerformed
        txtBuscar.setText("");
        cboTipoInsumo.setSelectedIndex(0);
        cargar_insumos(txtBuscar.getText());
    }//GEN-LAST:event_btnLimpiarActionPerformed

    private void txtRendimientoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtRendimientoKeyReleased
        actulizar_montos_particulares();
    }//GEN-LAST:event_txtRendimientoKeyReleased

    private void btnNuevoCategoria1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoCategoria1ActionPerformed
        operaciones_grupo_parttidas(2);
    }//GEN-LAST:event_btnNuevoCategoria1ActionPerformed

    private void btnLimpiar1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLimpiar1ActionPerformed
        dlgInsumos2 dialog = new dlgInsumos2(new javax.swing.JFrame(), true);
        int fila = tblInsumos.getSelectedRow();
        String valor = "";
        if (fila != -1) {
            valor = tblInsumos.getValueAt(fila, 0).toString();
        }
        dialog.seleccionar_base(valor);
        dialog.setVisible(true);
        cargar_insumos(txtBuscar.getText());
        metodos.seleccionar_tabla(tblInsumos, 0, valor);
    }//GEN-LAST:event_btnLimpiar1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(dlgPartidas3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(dlgPartidas3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(dlgPartidas3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(dlgPartidas3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the dialog
         */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                dlgPartidas3 dialog = new dlgPartidas3(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCopiarPartidasR;
    private javax.swing.JButton btnEliminarCategoria;
    private javax.swing.JButton btnEliminarPartidasR;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JButton btnLimpiar;
    private javax.swing.JButton btnLimpiar1;
    private javax.swing.JButton btnNuevoCategoria;
    private javax.swing.JButton btnNuevoCategoria1;
    private javax.swing.JButton btnNuevoPartidasR;
    private javax.swing.JButton btnOK;
    private javax.swing.JComboBox cboTipoInsumo;
    private javax.swing.JComboBox cboUnid;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    public javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JToolBar jToolBar2;
    private javax.swing.JTree jTree1;
    private javax.swing.JLabel label_total_1;
    private javax.swing.JLabel label_total_2;
    private javax.swing.JLabel label_total_3;
    private javax.swing.JLabel label_total_4;
    private javax.swing.JLabel label_total_5;
    private javax.swing.JLabel label_total_6;
    private javax.swing.JLabel label_total_7;
    private javax.swing.JLabel label_total_8;
    private javax.swing.JPanel panelAcu;
    private javax.swing.JTable tablaAcu;
    private javax.swing.JTable tablaPartidas;
    private javax.swing.JTable tblInsumos;
    private javax.swing.JTextField txtBuscar;
    private javax.swing.JTextField txtBuscar1;
    private javax.swing.JTextField txtCantidad;
    private javax.swing.JTextField txtCodigoInsumo;
    private javax.swing.JTextField txtCodigoPartida;
    private javax.swing.JTextField txtDescripcionInsumo;
    private javax.swing.JTextField txtNombrePartida;
    private javax.swing.JTextField txtPrecio;
    private javax.swing.JTextField txtRendimiento;
    private javax.swing.JTextField txtTotal;
    // End of variables declaration//GEN-END:variables
}
